public class Solution1254 {


    static int[][] directArr = new int[][]{new int[]{0, 1}, new int[]{1, 0}, new int[]{0, -1}, new int[]{-1, 0}};

    int m;

    int n;

    boolean[][] isTravel;

    private void init(final int[][] grid){
        this.m = grid.length;
        this.n = grid[0].length;
        this.isTravel = new boolean[m][n];
    }



    private boolean isClosedIsland(final int x, final int y, final int[][] grid){
        if (x < 0 || y < 0 || x >= m || y >= n) {
            return false;
        }
        if (grid[x][y] != 0 || isTravel[x][y]) {
            return true;
        }
        isTravel[x][y] = true;
        boolean res = true;
        for (int[] direct : directArr) {
            res &= isClosedIsland(x + direct[0], y + direct[1], grid);
        }
        return res;
    }

    public int closedIsland(int[][] grid) {
        init(grid);
        int res = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid[i][j] == 0 && !isTravel[i][j]){
                    if(isClosedIsland(i, j, grid)){
                        res++;
                    }
                }
            }
        }
        return res;
    }


    public static void main(String[] args) {
        Solution1254 s = new Solution1254();
        s.closedIsland(new int[][]{
                new int[]{1,1,1,1,1,1,1,0,},new int[]{1,0,0,0,0,1,1,0},new int[]{1,0,1,0,1,1,1,0},{1,0,0,0,0,1,0,1},{1,1,1,1,1,1,1,0}});
    }
}
